package com.personal.service.Impl;

import com.personal.dao.ProductDao;
import com.personal.dao.ProductImgDao;
import com.personal.dto.ImageHolder;
import com.personal.dto.ProductExecution;
import com.personal.entity.Product;
import com.personal.entity.ProductImg;
import com.personal.enums.ProductStateEnum;
import com.personal.exception.ProductCategoryOperationException;
import com.personal.exception.ProductOperationException;
import com.personal.service.ProductService;
import com.personal.utils.FileUtil;
import com.personal.utils.ImageUtil;
import com.personal.utils.PageCalculator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 萌新
 * @version 1.0
 * @date 2021/4/22 19:51
 */

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductDao productDao;

    @Autowired
    private ProductImgDao productImgDao;

    /**
     * 1. 处理缩略图，获取缩略图相对路径并赋值给product
     * 2. 往tb_product写入商品信息，获取productId
     * 3. 结合productId批量处理商品详情图
     * 4. 将商品详情图列表插入tb_product_img中
     * @param product
     * @param thumbnail
     * @param productImgList
     * @return
     * @throws ProductCategoryOperationException
     */
    @Override
    @Transactional
    public ProductExecution addProduct(Product product, ImageHolder thumbnail, List<ImageHolder> productImgList) throws ProductCategoryOperationException {
        if (product != null && product.getShop() != null && product.getShop().getShopId() != null && product.getProductCategory().getProductCategoryId() != null){
            //不为空的话，将设置默认的属性
            product.setCreateTime(new Date());
            product.setLastEditTime(new Date());
            //设置默认为展示
            product.setEnableStatus(1);
            //如果文件文件的输入流和文件名不为空，添加文件到指定目录，并且将相对路径设置给product，这样product就有了ImgAddr，为下一步的插入tb_product提供了数据来源
            if (thumbnail != null){
                addProductImg(product,thumbnail);
            }
            try {
                //写入tb_product
                int effectNum = productDao.insertProduct(product);
                if (effectNum <= 0){
                    throw new ProductCategoryOperationException("商品创建失败！");
                }
                //如果添加商品成功，继续处理商品详情图片，并写入tb_product_img
                if (productImgList != null && productImgList.size() > 0){
                    addProductDetailImgs(product,productImgList);
                }
                return new ProductExecution(ProductStateEnum.SUCCESS,product);
            }catch (Exception e){
                throw new ProductOperationException("创建商品失败：" + e.toString());
            }
        }else {
            return new ProductExecution(ProductStateEnum.NULL_PARAMETER);
        }
    }

    @Override
    public Product queryProductById(long productId) {
        return productDao.selectProductById(productId);
    }

    /**
     * 注意事务控制
     * @param product 商品信息
     * @param imageHolder 商品缩略图的封装信息
     * @param prodImgDetailList 商品详情图片的封装信息
     * @return
     * @throws ProductOperationException
     */
    @Override
    @Transactional
    public ProductExecution modifyProduct(Product product, ImageHolder imageHolder, List<ImageHolder> prodImgDetailList) throws ProductOperationException {
        if (product != null && product.getShop() != null && product.getShop().getShopId() != null){
            //设置默认的属性
            product.setLastEditTime(new Date());

            //1. 处理缩略图
            if (imageHolder != null){
                Product tempProduct = productDao.selectProductById(product.getProductId());
                //1.1 删除旧的缩略图
                if (tempProduct.getImgAddr() != null){
                    ImageUtil.deleteFileOrPath(tempProduct.getImgAddr());
                }
                //1.2 添加新的缩略图
                addProductImg(product, imageHolder);
            }

            //2. 处理商品详情

            //如果添加商品成功，继续处理商品详情图片，并写入tb_product_img
            if (prodImgDetailList != null && prodImgDetailList.size() > 0){
                //2.1 删除库表中productId对应的tb_product_img的信息
                deleteProductImgs(product.getProductId());
                //2.2 处理商品详情图片，并写入tb_product_img
                addProductDetailImgs(product,prodImgDetailList);
            }
            try {
                //3. 更新tb_product
                int effectNum = productDao.updateProduct(product);
                if (effectNum <= 0) {
                    throw new ProductOperationException("商品更新失败");
                }
                return new ProductExecution(ProductStateEnum.SUCCESS,product);
            }catch (Exception e){
                throw new ProductOperationException("商品更新失败：" + e.getMessage());
            }
        }else {
            return new ProductExecution(ProductStateEnum.NULL_PARAMETER);
        }
    }

    @Override
    public ProductExecution queryProductionList(Product productCondition, int pageIndex, int pageSize) throws ProductOperationException {
        List<Product> productList = null;
        int count = 0;
        try {
            // 将pageIndex  转换为Dao层识别的rowIndex
            int rowIndex = PageCalculator.calculateRowIndex(pageIndex,pageSize);
            productList = productDao.selectProductList(productCondition,rowIndex,pageSize);
            count = productDao.selectCountProduct(productCondition);
        }catch (Exception e){
            e.printStackTrace();
            new ProductExecution(ProductStateEnum.INNER_ERROR);
        }
        return new ProductExecution(ProductStateEnum.SUCCESS,productList,count);
    }

    /**
     * 处理商品详情图片，并写入tb_product_img
     * @param product
     * @param productImgList
     */
    private void addProductDetailImgs(Product product, List<ImageHolder> productImgList) {
        String relativePath = FileUtil.getShopImagePath(product.getShop().getShopId());
        //生成图片详情的图片，大一些，并且不添加水印，所以另外写了一个方法，基本和generateThumbnails相似
        List<String> imgAddrList = ImageUtil.generateNoralImgs(productImgList,relativePath);

        if (imgAddrList != null && imgAddrList.size() > 0) {
            List<ProductImg> productImgs = new ArrayList<>();
            for (String imgAddr : imgAddrList){
                ProductImg productImg = new ProductImg();
                productImg.setImgAddr(imgAddr);
                productImg.setProductId(product.getProductId());
                productImg.setCreateTime(new Date());
                productImgs.add(productImg);
            }
            try {
                int effectedNum = productImgDao.batchInsertProductImg(productImgs);
                if (effectedNum <= 0) {
                    throw new ProductOperationException("创建商品详情图片失败");
                }
            } catch (Exception e) {
                throw new ProductOperationException("创建商品详情图片失败:" + e.toString());
            }

        }

    }

    /**
     * 将商品的缩略图写到特定的shopId目录，并将imgAddr属性设置给product
     * @param product
     * @param thumbnail
     */
    private void addProductImg(Product product, ImageHolder thumbnail) {
        //根据shopId获取图片存储的相对路径
        String relativePath = FileUtil.getShopImagePath(product.getShop().getShopId());
        //添加图片到指定的目录
        String relativeAddr = ImageUtil.generateThumbnails(thumbnail,relativePath);
        //将relativeAddr设置给product
        product.setImgAddr(relativeAddr);
    }

    private void deleteProductImgs(Long productId){
        //获取该商铺下对应的productImg信息
        List<ProductImg> productImgList = productImgDao.selectProductImgList(productId);
        //遍历删除该目录下的全部文件
        for (ProductImg productImg : productImgList){
            ImageUtil.deleteFileOrPath(productImg.getImgAddr());
        }
        //删除tb_product_img中该productId对应的记录
        productImgDao.deleteProductImgById(productId);
    }


}
